﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using BLL;
using Entities;
using DAL;
using WindowsApp;
using DAL.IRepository;

namespace WindowsApp.QLTaiKhoan
{
    public partial class frmDangNhap : DevComponents.DotNetBar.Office2007Form
    {
        IGeneralRepository<TaiKhoan> _repository;
        TaiKhoanManager _manager;
        TaiKhoan _tk;
        public frmDangNhap()
        {
            InitializeComponent();
            _repository = new GeneralRepository<TaiKhoan>();
            _manager = new TaiKhoanManager(_repository);
        }

        private void btnDangNhap_Click(object sender, EventArgs e)
        {
            _tk = new TaiKhoan();
            _tk.Username = txtUserName.Text;
            _tk.Password = txtPassWord.Text;
            _tk.PhanQuyen = cbbPhanQuyen.SelectedItem.ToString();
            var vResult = _manager.Validate(_tk);
            if (vResult.Valid)
            {
                var aResult = _manager.Find(s => s.Username.ToLower().CompareTo(txtUserName.Text.ToLower()) == 0);
                if (aResult.Success)
                {
                    TaiKhoan tk = aResult.Result[0];
                    if ( tk.Password == _tk.Password && tk.PhanQuyen.ToLower() == _tk.PhanQuyen.ToLower())
                    {
                        //MessageBox.Show("Đăng nhập thành công","Đăng nhập");
                        frmFormChuongTrinh frm = new frmFormChuongTrinh();
                        frm._tk = tk;
                        this.Hide();
                        frm.ShowDialog();
                        this.Close();
                    }
                    else
                        MessageBox.Show("Mật khẩu hoặc phân quyền không đúng, vui lòng nhập lại","Lỗi đăng nhập");
                }
                else
                {
                    MessageBox.Show(aResult.GetErrorMessages());

                }
            }
            else
                MessageBox.Show(vResult.ToString());

        }
        

        private void frmDangNhap_Load(object sender, EventArgs e)
        {
            cbbPhanQuyen.SelectedIndex = 0;
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            txtPassWord.ResetText();
            txtUserName.ResetText();
            cbbPhanQuyen.ResetText();
            txtUserName.Focus();
        }
    }
}